package com.alibaba.citrus.cr.platform.enhance.facade.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.alibaba.acm.shaded.com.alibaba.metrics.StringUtils;
import com.alibaba.acm.shaded.com.google.common.collect.Lists;
import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.platform.enhance.functions.customer.CustomerAddressRelationEntity;
import com.alibaba.citrus.cr.platform.enhance.functions.customer.CustomerSaleScopeEntity;
import com.alibaba.citrus.cr.platform.enhance.repository.CustomerSaleScopeRepository;
import com.alibaba.citrus.cr.platform.enhance.repository.model.DubboResult;
import com.alibaba.citrus.cr.platform.enhance.repository.utils.ResultUtils;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.message.ErrorMessage;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;

import com.epoch.app.bcorder.model.dto.BaselineBatchQueryPlatforms2Request;
import com.epoch.app.bcorder.model.dto.BaselineGetEmployeeRolesById2Request;
import com.epoch.app.bcorder.model.dto.BaselineGetEmployeesEs2Request;
import com.epoch.app.bcorder.model.dto.BaselineGetEmployeesEsRequest;
import com.epoch.app.bcorder.model.dto.EmployeeSDO;
import com.epoch.app.bcorder.model.dto.GetEmployeeOrganizationsRequest;
import com.epoch.app.bcorder.model.dto.PlatformSDO;
import com.epoch.app.bcorder.model.dto.RoleSDO;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.BcOrderService;
import com.epoch.app.crplatformenhance.api.customeraddresswrite.service.CustomerAddressWriteService;
import com.epoch.app.crplatformenhance.api.customersalescopewrite.dto.CustomerSalesRangeImportRequest;
import com.epoch.app.crplatformenhance.api.customersalescopewrite.dto.CustomerSalesRangeImportResponse;
import com.epoch.app.crplatformenhance.api.customersalescopewrite.service.CustomerSaleScopeWriteService;
import com.epoch.app.crplatformenhance.enums.OrganizationTypeEnum;
import com.epoch.app.crplatformenhance.model.dto.GetEmployeeRolesRequest;
import com.epoch.app.crplatformenhance.model.dto.GetOrganiztionById2Request;
import com.epoch.app.crplatformenhance.model.dto.ImportCustomerSaleScopeSDO;
import com.epoch.app.crplatformenhance.sdo.CustomerAddressSDO;
import com.epoch.app.crplatformenhance.sdo.CustomerSaleScopeSDO;
import com.epoch.app.crplatformenhance.sdo.OrganizationSDO;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

@Primary
@Service
public class CustomerSaleScopeWriteServiceImpl implements CustomerSaleScopeWriteService {
    private static final Log log = Log.getLogger(CustomerSaleScopeWriteServiceImpl.class);

    @Resource
    private BcOrderService bcOrderService;
    @Resource
    private BaseDataService baseDataService;
    @Resource
    private CustomerSaleScopeRepository customerSaleScopeRepository;
    @Resource
    private CrPlatformEnhanceService crPlatformEnhanceService;

    @Override
    @FacadeInvoker
    public Result<Boolean> editCustomerSaleScope(CustomerSaleScopeSDO saleScopeSDO) {
        if (CollectionUtils.isNotEmpty(saleScopeSDO.getCustomerPrincipalList()) && saleScopeSDO.getCustomerPrincipalList().size()>5) {
            throw new FacadeException("OTS-01-004-02-15-008");
        }
        CustomerSaleScopeSDO load = customerSaleScopeRepository.load(saleScopeSDO.getId());
        if (Objects.isNull(load)) {
            throw new FacadeException("OTS-01-004-02-15-003");
        }
        load.setOrgSaleDepartmentCode(saleScopeSDO.getOrgSaleDepartmentCode());
        load.setOrgSaleChannelCode(saleScopeSDO.getOrgSaleChannelCode());
        GetOrganiztionById2Request getSaleDepartmentById2Request = GetOrganiztionById2Request.builder().id(saleScopeSDO.getOrgSaleDepartmentCode()).build();
        GetOrganiztionById2Request getSaleChannelById2Request = GetOrganiztionById2Request.builder().id(saleScopeSDO.getOrgSaleChannelCode()).build();
        OrganizationSDO saleDepartmentSDO = null;
        OrganizationSDO saleChannelSDO = null;
        try {
            saleDepartmentSDO = crPlatformEnhanceService.getOrganiztionById2(getSaleDepartmentById2Request).getResult();
            saleChannelSDO = crPlatformEnhanceService.getOrganiztionById2(getSaleChannelById2Request).getResult();
        } catch (Exception e) {
            log.info("CustomerSaleScopeWriteServiceImpl.editCustomerSaleScope.getOrganiztionById2查询失败:" + JSONObject.toJSONString(saleScopeSDO));
        }
        if (Objects.isNull(saleDepartmentSDO) && saleDepartmentSDO.getId() == null) {
            throw new FacadeException("OTS-01-004-02-15-004");
        }
        if (Objects.isNull(saleChannelSDO) && saleChannelSDO.getId() == null) {
            throw new FacadeException("OTS-01-004-02-15-004");
        }
        load.setPrincipal(saleScopeSDO.getPrincipal());
        if (StringUtil.isNotEmpty(load.getFeatures())) {
            JSONObject jsonObject = JSONObject.parseObject(load.getFeatures());
            jsonObject.put("orgSalesDepartmentName", saleDepartmentSDO.getName());
            jsonObject.put("outOrgSalesChannelName", saleChannelSDO.getName());
            load.setFeatures(jsonObject.toJSONString());
        }
        load.setCommercePlatform(saleScopeSDO.getCommercePlatform());

        //校验客户方负责人员工角色
        load.setCustomerPrincipalList(saleScopeSDO.getCustomerPrincipalList());
        CustomerAddressRelationEntity customerAddressRelationEntity = CustomerAddressRelationEntity.of(load);
        customerAddressRelationEntity.checkEmployeeCustomerRole(load.getCustomerPrincipalList());

        //更新售达方
        CustomerSaleScopeEntity saleScopeEntity = CustomerSaleScopeEntity.of(load);
        Boolean result = saleScopeEntity.edit();
        //更新客户方负责人
        Boolean b = customerAddressRelationEntity.saveCustomerSaleScopePrincipal();

        return Result.success(result);
    }

    /**
     * 导入客户销售范围
     *
     * @param customerSalesRangeImportRequest
     * @return
     */
    @Override
    @FacadeInvoker
    public CustomerSalesRangeImportResponse customerSalesRangeImport(CustomerSalesRangeImportRequest customerSalesRangeImportRequest) {
        if (Objects.isNull(customerSalesRangeImportRequest) || CollectionUtils.isEmpty(customerSalesRangeImportRequest.getRequestList())) {
            throw new FacadeException("OTS-01-004-02-16-001");
        }
        List<ImportCustomerSaleScopeSDO> requestList = customerSalesRangeImportRequest.getRequestList();
        for (ImportCustomerSaleScopeSDO importCustomerSaleScopeSDO : requestList) {
            //判断必填的字段
            if (Strings.isBlank(importCustomerSaleScopeSDO.getId())) {
                importCustomerSaleScopeSDO.setErrorMessage(ErrorMessage.code("OTS-01-004-02-16-009", null).getDisplayErrorMessage());
                continue;
            }
//            if (Strings.isBlank(importCustomerSaleScopeSDO.getOrgSaleDepartmentCode())) {
//                importCustomerSaleScopeSDO.setErrorMessage(ErrorMessage.code("OTS-01-004-02-16-002", null).getDisplayErrorMessage());
//                continue;
//            }
//            if (Strings.isBlank(importCustomerSaleScopeSDO.getOrgSaleChannelCode())) {
//                importCustomerSaleScopeSDO.setErrorMessage(ErrorMessage.code("OTS-01-004-02-16-021", null).getDisplayErrorMessage());
//                continue;
//            }
            /*if (Strings.isBlank(importCustomerSaleScopeSDO.getPrincipal())) {
                importCustomerSaleScopeSDO.setErrorMessage(ErrorMessage.code("OTS-01-004-02-16-003", null).getDisplayErrorMessage());
                continue;
            }*/

            //根据id查询原数据
            CustomerSaleScopeSDO load = customerSaleScopeRepository.load(importCustomerSaleScopeSDO.getId());
            if (Objects.isNull(load)) {
                importCustomerSaleScopeSDO.setErrorMessage(ErrorMessage.code("OTS-01-004-02-16-010", null).getDisplayErrorMessage());
                continue;
            }

            //判断是否导入平台字段 校验非必填 但是如果填了要进行校验
            String commercePlatformName = importCustomerSaleScopeSDO.getCommercePlatform();
            String commercePlatformCode = importCustomerSaleScopeSDO.getCommercePlatformCode();
            if (StringUtils.isNotBlank(commercePlatformName) || StringUtils.isNotBlank(commercePlatformCode)) {
                BaselineBatchQueryPlatforms2Request baselineBatchQueryPlatforms2Request = new BaselineBatchQueryPlatforms2Request();
                if(StringUtils.isNotBlank(commercePlatformCode)){
                    baselineBatchQueryPlatforms2Request.setPlatformCodes(Lists.newArrayList(commercePlatformCode));
                }else{
                    baselineBatchQueryPlatforms2Request.setPlatformNames(Lists.newArrayList(commercePlatformName));
                }
                Result<List<PlatformSDO>> result = baseDataService.baselineBatchQueryPlatforms2(baselineBatchQueryPlatforms2Request);
                if (CollectionUtils.isEmpty(result.getResult())) {
                    importCustomerSaleScopeSDO.setErrorMessage(ErrorMessage.code("OTS-01-004-02-16-024", null).getDisplayErrorMessage());
                    continue;
                }
                PlatformSDO platformSDO = result.getResult().get(0);
                load.setCommercePlatform(platformSDO.getPlatformId());
            }

            //查询销售负责人信息
            String principalNick = importCustomerSaleScopeSDO.getPrincipal();
            String principalName = importCustomerSaleScopeSDO.getPrincipalName();
            if(StringUtils.isNotBlank(principalNick) || StringUtils.isNotBlank(principalName)) {
                BaselineGetEmployeesEsRequest baselineGetEmployeesEsRequest = new BaselineGetEmployeesEsRequest();
                if(StringUtils.isNotBlank(principalNick)){
                    baselineGetEmployeesEsRequest.setNick(principalNick);
                }else{
                    baselineGetEmployeesEsRequest.setName(principalName);
                }
                DubboResult result = ResultUtils.getBaseLineDubboResult((Map) baseDataService.baselineGetEmployeesEs(baselineGetEmployeesEsRequest));
                List<Map<String, Object>> employeeList = (List) result.getResult();
                if (Objects.isNull(employeeList) || CollectionUtils.isEmpty(employeeList)) {
                    importCustomerSaleScopeSDO.setErrorMessage(ErrorMessage.code("OTS-01-004-02-16-025", null).getDisplayErrorMessage());
                    continue;
                }
                //员工名称查询 es模糊搜索 需要过滤
                if(StringUtils.isNotBlank(baselineGetEmployeesEsRequest.getName())){
                    employeeList = employeeList.stream().filter(x->{
                        Map employeeMap = (Map) x.get("employeeSDO");
                        if(principalName.equals(employeeMap.get("name"))){
                            return true;
                        }else{
                            return false;
                        }
                    }).collect(Collectors.toList());
                }
                Map<String, Object> employeeSDO = employeeList.get(0);
                //获取销售负责人的所属部门、所属渠道
                if (employeeSDO != null) {
                    Map employee = (Map) employeeSDO.get("employeeSDO");
                    load.setPrincipal(employee.get("id").toString());
                    GetEmployeeOrganizationsRequest getEmployeeOrganizationsRequest = new GetEmployeeOrganizationsRequest();
                    getEmployeeOrganizationsRequest.setEmployeeId(employee.get("id").toString());
                    DubboResult result2 = ResultUtils.getDubboResultList((Map) bcOrderService.getEmployeeOrganizations(getEmployeeOrganizationsRequest));
                    List<Map<String, Map<String, Object>>> employeeOrgList = (List) result2.getResult();
                    if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(employeeOrgList)) {
                        //若销售负责人的账号所属组织的组织类型为【销售部门】，则带值销售渠道、销售部门；
                        //若销售负责人的账号所属组织的组织类型为【销售渠道】，则仅带值销售渠道；
                        //若销售负责人的账号所属组织的组织类型为其他，则不带值；
                        Map<String, Object> organization = employeeOrgList.get(0).get("organizationSDO");
                        String orgType = organization.get("type").toString();
                        if (OrganizationTypeEnum.SALES_DEPARTMENT.getCode().toString().equals(orgType)) {
                            load.setOrgSaleDepartmentCode(organization.get("id").toString());
                            load.setOrgSaleChannelCode(organization.get("parentId").toString());
                        }else if(OrganizationTypeEnum.SALES_CHANNEL.getCode().toString().equals(orgType)) {
                            load.setOrgSaleDepartmentCode("");
                            load.setOrgSaleChannelCode(organization.get("id").toString());
                        }else{
                            load.setOrgSaleDepartmentCode("");
                            load.setOrgSaleChannelCode("");
                        }
                    }
                }
            }

            //查询客户方负责人信息
            String customerPrincipalNick = importCustomerSaleScopeSDO.getCustomerPrincipal();

            CustomerSaleScopeSDO sdo = new CustomerSaleScopeSDO();
            sdo.setId(importCustomerSaleScopeSDO.getId());
            sdo.setCustomerCode(load.getCustomerCode());
            CustomerAddressRelationEntity customerAddressRelationEntity = CustomerAddressRelationEntity.of(sdo);

            if(StringUtils.isNotBlank(customerPrincipalNick)) {
                String[] customerPrincipalArray = customerPrincipalNick.split(",|，");
                if (customerPrincipalArray.length > 5) {
                    importCustomerSaleScopeSDO.setErrorMessage(ErrorMessage.code("OTS-01-004-02-15-008").getDisplayErrorMessage());
                    continue;
                }
                Map<String,List<String>> customerPrincipalMap = customerAddressRelationEntity.queryEmployeeIdsByNicks(Lists.newArrayList(customerPrincipalArray));
                if(customerPrincipalMap.get("errorEmployees") != null){
                    importCustomerSaleScopeSDO.setErrorMessage(ErrorMessage.code("OTS-01-004-02-16-026", "账号",customerPrincipalMap.get("errorEmployees").toString()).getDisplayErrorMessage());
                    continue;
                }else if(customerPrincipalMap.get("errorEmployeeRoles") != null){
                    importCustomerSaleScopeSDO.setErrorMessage(ErrorMessage.code("OTS-01-004-02-16-027", "账号角色",customerPrincipalMap.get("errorEmployeeRoles").toString()).getDisplayErrorMessage());
                    continue;
                }
                sdo.setCustomerPrincipalList(customerPrincipalMap.get("ids"));
            }

            //修改客户方负责人
            Boolean b = customerAddressRelationEntity.saveCustomerSaleScopePrincipal();

            //修改
            CustomerSaleScopeEntity saleScopeEntity = CustomerSaleScopeEntity.of(load);
            saleScopeEntity.edit();
        }
        return CustomerSalesRangeImportResponse.builder().requesltList(requestList).build();
    }

}
